//
//  UIImageView+Extend.m
//  SmallElephant
//
//  Created by Faith on 2019/1/7.
//  Copyright © 2019 Faith. All rights reserved.
//

#import "UIImageView+Extend.h"
#import "UIImage+Extend.h"

@implementation UIImageView (Extend)

+ (UIImageView *)withImage:(NSString *)name {
    return [UIImageView withImage:name type:@"png"];
}

+ (UIImageView *)withImage:(NSString *)name type:(NSString *)type {
    return [[UIImageView alloc] initWithImage:[UIImage imageWithName:name type:type]];
}

- (void)setImageUrl:(NSString *)imageUrl {
    self.contentMode = IMAGE_MODE;
    if(!imageUrl || imageUrl.length==0) {
        [self setImage:[UIImage imageWithName:@"icon-avatar-empty@3x"]];
    } else {
        if([imageUrl hasPrefix:@"http"]) {
            [self sd_setImageWithURL:[NSURL URLWithString:imageUrl] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                if(error) {
                    [self setImage:[UIImage imageWithName:@"icon-avatar-empty@3x"]];
                }
            }];
        } else {
            imageUrl = [NSString stringWithFormat:@"%@%@", BASE_IMAGE_URL, imageUrl];
            [self sd_setImageWithURL:[NSURL URLWithString:imageUrl] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                if(error) {
                    [self setImage:[UIImage imageWithName:@"icon-avatar-empty@3x"]];
                }
            }];
        }
    }
}

@end
